package com.fp.m7.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fp.m7.api.util.Clock;
import com.fp.m7.model.EntityBase;

@Repository("baseDao")
public class BaseDaoImpl<T extends EntityBase> implements BaseDao<T> {

    @PersistenceContext
    protected EntityManager em;

    protected Class<?> clazz;
    
    @Autowired
    protected Clock clock;

    public BaseDaoImpl(Class<?> clazz) {
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T getById(Long id) {
        return (T) em.find(clazz, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> listAll() {
        return em.createQuery("from " + clazz.getName()).getResultList();
    }

    @Override
    public T persist(T object) {
    	prePersist(object);
        em.persist(object);
        return object;
    };

    @Override
    public T merge(T object) {
        return em.merge(object);
    };

    @Override
    public T refresh(T object) {
        em.refresh(object);
        return object;
    };

    @Override
    public void remove(T object) {
        em.remove(object);
    };

    @Override
    public void flush() {
        em.flush();
    }
    
    private void prePersist(T object) {
    	object.setAuditCD(clock.getDate());
    }
}
